import { ChangeDetectorRef, Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { STChange, STColumn, STComponent, STData } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { NzFormatEmitEvent, NzTreeNode, NzTreeNodeOptions } from 'ng-zorro-antd/tree';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { map, tap } from 'rxjs/operators';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-organ-user',
  templateUrl: './user.component.html',
})
export class OrganUserComponent implements OnInit {
  form: FormGroup;
  nodes = [];
  q = {
    pi: 1,
    ps: 10,
    no: '',
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];
  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 1,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 3, text: '异常', value: false, type: 'error', checked: false },
  ];
  @ViewChild('st', { static: true })
  st: STComponent;
  columns: STColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '用户账号', index: 'no' },
    { title: '用户姓名', index: 'description' },
    { title: '电子邮箱', index: 'description' },
    { title: '手机号码', index: 'description' },
    { title: '所属公司', index: 'description' },
    { title: '所属部门', index: 'description' },
    { title: '性别', index: 'description' },
    {
      title: '状态',
      index: 'status',
      render: 'status',
      filter: {
        menus: this.status,
        fn: (filter, record) => record.status === filter.index,
      },
    },
    {
      title: '更新时间',
      index: 'updatedAt',
      type: 'date',
    },
    {
      title: '操作',
      buttons: [
        {
          text: '配置',
          click: (item) => this.msg.success(`配置${item.no}`),
        },
        {
          text: '订阅警报',
          click: (item) => this.msg.success(`订阅警报${item.no}`),
        },
      ],
    },
  ];
  selectedRows: STData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;
  userGender: Array<{ value: string; label: string }> = [
    { value: '0', label: '男' },
    { value: '1', label: '女' },
  ];
  expandKeys = ['0-0'];
  value?: string;
  company = [];
  nodeCompany = [];
  organ = [];
  nodeOrgan = [];
  organDisabled = true;
  post: Array<{ value: string; label: string }> = [
    { value: '0', label: '董事长' },
    { value: '1', label: 'CEO' },
    { value: '2', label: 'CTO' },
  ];
  organName: string;
  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private cdr: ChangeDetectorRef,
    private fb: FormBuilder,
  ) {
    this.form = this.fb.group({
      userName: [null, [Validators.required]],
      realName: [null, [Validators.required]],
      userEmail: [undefined, [Validators.required]],
      userMobile: [null, [Validators.required]],
      userGender: [null, [Validators.required]],
      userStatus: [null, [Validators.required]],
      standard: [null],
      postName: [null, [Validators.required]],
      userCompany: [null, [Validators.required]],
      organName: [null, [Validators.required]],
    });
  }

  ngOnInit(): void {
    // this.getData();
    // 获取上层机构
    this.getTreeMenu();
  }
  getTreeMenu(): void {
    // 获取上层机构
    this.http.post('api/organ/getOrganizeTree').subscribe((res) => {
      this.nodes = res.data;
    });
  }

  getTreeCompany(): void {
    this.http.post('api/organ/getCompanyList').subscribe((res) => {
      res.data.forEach((item) => {
        this.nodeCompany.push(
          new NzTreeNode({
            title: item.organName,
            key: item.id,
            children: [],
          }),
        );
      });
      this.company = this.nodeCompany;
    });
  }

  getData(): void {
    this.loading = true;
    this.q.statusList = this.status.filter((w) => w.checked).map((item) => item.index);
    if (this.q.status !== null && this.q.status > -1) {
      this.q.statusList.push(this.q.status);
    }
    this.http
      .get('/rule', this.q)
      .pipe(
        map((list: Array<{ status: number; statusText: string; statusType: string }>) =>
          list.map((i) => {
            const statusItem = this.status[i.status];
            i.statusText = statusItem.text;
            i.statusType = statusItem.type;
            return i;
          }),
        ),
        tap(() => (this.loading = false)),
      )
      .subscribe((res) => {
        this.data = res;
        this.cdr.detectChanges();
      });
  }

  stChange(e: STChange): void {
    switch (e.type) {
      case 'checkbox':
        this.selectedRows = e.checkbox;
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.callNo, 0);
        this.cdr.detectChanges();
        break;
      case 'filter':
        this.getData();
        break;
    }
  }

  remove(): void {
    this.http.delete('/rule', { nos: this.selectedRows.map((i) => i.no).join(',') }).subscribe(() => {
      this.getData();
      this.st.clearCheck();
    });
  }

  approval(): void {
    this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
  }

  add(tpl: TemplateRef<{}>): void {
    this.getTreeCompany();

    this.modalSrv.create({
      nzTitle: '新建员工',
      nzContent: tpl,
      nzWidth: 1100,
      nzOnOk: () =>
        new Promise((resolve) => {
          for (const i in this.form.controls) {
            this.form.controls[i].markAsDirty();
            this.form.controls[i].updateValueAndValidity();
          }

          let flag = false;
          if (this.form.valid) {
            this._submitForm();
            flag = this.form.valid;
          }

          resolve(flag);
        }),
    });
  }

  reset(): void {
    // wait form reset updated finished
    setTimeout(() => this.getData());
  }
  onExpandChange(e: NzFormatEmitEvent): void {
    const node = e.node;
    if (node && node.getChildren().length === 0 && node.isExpanded) {
      this.loadNode(node.key).then((data) => {
        node.addChildren(data);
      });
    }
  }
  onOrganExpandChange(e: NzFormatEmitEvent): void {
    const node = e.node;
    if (node && node.getChildren().length === 0 && node.isExpanded) {
      this.loadOrganNode(node.key).then((data) => {
        node.addChildren(data);
      });
    }
  }

  loadOrganNode(key: string): Promise<NzTreeNodeOptions[]> {
    return new Promise((resolve) => {
      this.http
        .post('api/organ/getCompanyListByParentId', {
          parentId: key,
          orgType: 2,
        })
        .subscribe((res) => {
          const nodeArray = new Array();
          res.data.forEach((item) => {
            nodeArray.push(
              new NzTreeNode({
                title: item.organName,
                key: item.id,
                children: [],
              }),
            );
          });
          resolve(nodeArray);
        });
    });
  }

  loadNode(key: string): Promise<NzTreeNodeOptions[]> {
    return new Promise((resolve) => {
      this.http
        .post('api/organ/getCompanyListByParentId', {
          parentId: key,
          orgType: 1,
        })
        .subscribe((res) => {
          const nodeArray = new Array();
          res.data.forEach((item) => {
            nodeArray.push(
              new NzTreeNode({
                title: item.organName,
                key: item.id,
                children: [],
              }),
            );
          });
          resolve(nodeArray);
        });
    });
  }

  nzEvent(event: NzFormatEmitEvent): void {
    console.log(event);
  }
  nzCompanEvent(event: NzFormatEmitEvent): void {
    console.log(event);
    this.loadOrgan(event.node.key);
  }

  loadOrgan(key: string): void {
    this.nodeOrgan = [];
    // 获取当前公司下所属机构
    this.http
      .post('api/organ/getCompanyListByParentId', {
        parentId: key,
        orgType: 2,
      })
      .subscribe((res) => {
        res.data.forEach((item) => {
          this.nodeOrgan.push(
            new NzTreeNode({
              title: item.organName,
              key: item.id,
              children: [],
            }),
          );
        });
        this.organ = this.nodeOrgan;
        this.organDisabled = false;
      });
  }

  _submitForm(): void {
    const params = {
      userName: this.form.controls.userName.value,
      realName: this.form.controls.realName.value,
      userEmail: this.form.controls.userEmail.value,
      userMobile: this.form.controls.userMobile.value,
      userGender: this.form.controls.userGender.value,
      userStatus: this.form.controls.userStatus.value,
      userCompany: this.form.controls.userCompany.value,
      organName: this.form.controls.organName.value,
      postName: this.form.controls.postName.value,
      standard: this.form.controls.standard.value,
    };

    this.http.post('api/user/insertUser', params).subscribe((res) => {
      if (res.code === 200) {
        this.msg.success('操作成功');
        this.getData();
      }
    });
  }
}
